package com.huatai.exchange.bootup.task;

import com.faneui.common.bean.FaneuiBaseResp;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.*;
import com.faneui.integration.smb.SmbFileUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.huatai.exchange.dal.model.ExcFileLoadInfo;
import com.huatai.exchange.dal.model.ExcFileLoadRecord;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.facade.enums.LoadRecordStatusEnum;
import com.huatai.exchange.integration.base.service.FileOperateService;
import com.huatai.exchange.service.ExcFileLoadInfoService;
import com.huatai.exchange.service.ExcFileLoadRecordService;
import com.huatai.exchange.service.FileLoadService;
import com.huatai.exchange.utils.FileDealUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import jcifs.smb.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping(value = "task")
@Api("任务")
public class BackupFileTask {

    private static final Logger logger = LoggerFactory.getLogger(BackupFileTask.class);

    @Value("${tmp_file_path}")
    private String tmpFilePath;

    @Autowired
    private ExcFileLoadRecordService excFileLoadRecordService;

    @Autowired
    private ExcFileLoadInfoService excFileLoadInfoService;

    @Autowired
    private FileOperateService fileOperateService;

    @Autowired
    private FileLoadService fileLoadService;


    @ApiModelProperty
    @RequestMapping(value = "/file/load", method = RequestMethod.GET)
    @ResponseBody
    public FaneuiBaseResp loadThirdFile(@RequestParam(required = false) String occurDate) throws BusinessException {
        FaneuiBaseResp resp = new FaneuiBaseResp();
        if (StringUtils.isBlank(occurDate)) {
            occurDate = DateFormatUtils.yyyyMMdd.format(new Date());
        }
        NtlmPasswordAuthentication auth = SmbFileUtils.createAuthHdisk();
        List<ExcFileLoadInfo> fileLoadInfos = excFileLoadInfoService.queryExcFileNeedLoadInfoList();
        for (ExcFileLoadInfo loadInfo : fileLoadInfos) {
            ExcFileLoadRecord record = excFileLoadRecordService.queryExcFileLoadRecord(loadInfo.getId(), occurDate);
            if (record == null) {
                excFileLoadRecordService.addExcFileLoadRecord(loadInfo.getId(), occurDate);
                record = excFileLoadRecordService.queryExcFileLoadRecord(loadInfo.getId(), occurDate);
            }
            if (LoadRecordStatusEnum.S.toString().equals(record.getStatus()) || LoadRecordStatusEnum.R.toString().equals(record.getStatus())) {
                logger.info("成功处理或者处理中");
                continue;
            }
            // 判断时间是否在开始 加载
            if (Integer.valueOf(DateFormatUtils.HHmmss.format(new Date())) < Integer.valueOf(loadInfo.getStartTime())) {
                logger.info("时间未到");
                continue;
            }
            Long num = excFileLoadRecordService.modifyRecordStatus(record.getId(), record.getStatus(), "R","正在处理中");
            if (num == 0) {
                logger.info("其他线程处理中");
                continue;
            }
            Map<String, Object> resvMap = Maps.newHashMap();
            resvMap.put("YYYYMMDD", occurDate);
            String localFilePath = tmpFilePath + UUID.randomUUID().toString();
            File localFile = new File(localFilePath);
            try {
                long statTime = System.currentTimeMillis();
                String srcPath = FileDealUtils.formatStr(loadInfo.getSrcPath(), resvMap);// 目标H地址
                String srcName = FileDealUtils.formatStr(loadInfo.getSrcName(), resvMap);// 目标名称
                SmbFile smbDir = new SmbFile(srcPath, auth);
                List<String> smbFileNames = Lists.newArrayList(smbDir.list());
                logger.info("开始处理");
                // 校验标志文件是否到
                fileLoadService.checkFileAvailableMark(loadInfo, smbFileNames, resvMap); // 标志文件 是否
                // 如果是多个文件的话，下载并压缩好
                if (Contents.boolean_true.equals(loadInfo.getMoreFlag())) {
                    fileLoadService.downloadAndZipFiles(localFilePath, srcName, srcPath, smbFileNames, resvMap);
                } else {
                    String smbFileUrl = srcPath + srcName;
                    SmbFileUtils.copyLocalFileFromRemote(localFile, smbFileUrl, auth);
                }
                String filePath = fileOperateService.uploadFile(localFile);

                record.setFilePath(filePath);
                record.setStatus(LoadRecordStatusEnum.S.toString());
                Long endTime = System.currentTimeMillis();
                record.setCostTime(Long.valueOf((endTime - statTime) / 100).intValue());
                record.setMemo("");
                excFileLoadRecordService.modifyExcFileLoadRecord(record);
            } catch (Exception ex) {
                String memo = ex.getMessage();
                excFileLoadRecordService.modifyRecordStatus(record.getId(), LoadRecordStatusEnum.R.toString(), LoadRecordStatusEnum.I.toString(), memo);
            }finally {
                localFile.deleteOnExit();
            }
        }
        return resp;
    }

}
